package com.cloudm.technician.ui.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.cloudm.technician.R;
import com.cloudm.technician.extensions.ContextExtensionsKt;
import com.cloudm.technician.ui.base.BaseApplication;

import java.io.File;

/**
 * 作者: wesley
 * 时间: 2017/12/26
 * 描述: 版本更新服务
 */
public class VersionUpdateService extends Service {

    private BroadcastReceiver receiver;
    private static final String APK_NAME = "install_treasure.apk";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return Service.START_NOT_STICKY;
        }
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return Service.START_NOT_STICKY;
        }
        String url = bundle.getString("url");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                unregisterReceiver(receiver);
                resetData(context);
                intent = new Intent(Intent.ACTION_VIEW);
                File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                        APK_NAME);
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(context,
                            context.getPackageName() + ".fileProvider", file);
                } else {
                    uri = Uri.fromFile(file);
                }
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                startActivity(intent);
                stopSelf();
            }
        };
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        startDownload(url);
        return Service.START_STICKY;
    }

    //开始下载apk
    private void startDownload(String url) {
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle(AppUtils.getAppName());
        request.setDescription(getResources().getString(R.string.down_load_apk));
        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, APK_NAME);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        if (downloadManager != null) {
            downloadManager.enqueue(request);
        }
    }

    //重置数据
    private void resetData(Context context) {
        BaseApplication application = ContextExtensionsKt.getBaseApplication(context);
        if (application != null) {
            application.getAppComponent().getPreferenceHelper().setFirstTimeIn(true);
            application.getAppComponent().getPreferenceHelper().setLogin(false);
            application.getAppComponent().getDbHelper().deleteAllData();
        }
    }
}
